package com.bdqn.utli;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bdqn.bean.bo.TokenPayloadBo;

import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 忍
 * @title: JwtUtil
 * @projectName Teaching
 * @description: TODO
 * @date 2019/5/2014:52
 */
public class JwtUtil {
    //设置过期时间为15分钟
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    //设置token私钥
    private static final String TOKEN_SECRET = "yuelaiyuebudong";

    /**
     * @description: 生成签名15分钟后过期
     * @param userName:用户名, userId：用户Id
     * @return java.lang.String 加密的token
     * @throws UnsupportedEncodingException
     * @author Mr.Zhou
     * @date 2019/5/20 15:24
     */
    public static String sign(String userId){
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            //私钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String ,Object> header = new HashMap<>(2);
            header.put("typ","JWT");
            header.put("alg","HS256");
            //附带username,userId信息，生成签名
            return JWT.create()
                    .withHeader(header)
//                    .withClaim("loginName",userName)
                    .withClaim("USerId",userId)
                    .withExpiresAt(date)
                    .sign(algorithm);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(sign("55"));
    }
    /**
     * @description: 校验token是否正确
     * @param token
     * @return boolean
     * @throws
     * @author Mr.Zhou
     * @date 2019/5/21 8:39
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * @description:获取token中用户的身份状态
     * @param token
     * @return boolean
     * @throws
     * @author Mr.Zhou
     * @date 2019/6/21 10:18
     */
    public static TokenPayloadBo payload(String token){
        String[] split = token.split("\\.");
        String encodedPayload = split[1];
        try {
            String jsonPayload = base64Decode(encodedPayload);
              TokenPayloadBo tokenPayloadBo = JSON.parseObject(jsonPayload,TokenPayloadBo.class);
              return tokenPayloadBo;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String base64Decode(String data) throws UnsupportedEncodingException {
        final Base64.Decoder decoder = Base64.getDecoder();
        return new String(decoder.decode(data), "UTF-8");
    }
}
